package com.poker.controller;

import com.poker.entity.Permission;
import com.poker.service.PermissionService;
import com.poker.util.Misc;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: yuanZ;
 * @Date: 2018/8/8 10:20;
 * @Description: 权限管理;
**/
@Controller
@RequestMapping("/managerPermission")
public class PermissionController extends BaseController {

    @Resource
    private PermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model, Permission permission,
                       @RequestParam(defaultValue = "0") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
        Page<Permission> data = permissionService.findPermissionNoCriteria(page, size);
        model.addAttribute("data", data);
        model.addAttribute("permission", permission);
        return managerPage("permission/list");
    }

    @RequestMapping("/findPermissionQuery")
    public String findPermissionQuery(Model model , Permission permission,
                                @RequestParam(defaultValue = "0") Integer page,
                                @RequestParam(defaultValue = "10") Integer size) {
        Page<Permission> data = permissionService.findPermissionCriteria(page, size, permission);
        model.addAttribute("data", data);
        model.addAttribute("permission", permission);
        return managerPage("permission/list");
    }

    @RequestMapping("/delete")
    public String delete(String id, Integer page) {
        permissionService.deleteById(id);
        return redirect("/managerPermission/list?page=" + page);
    }

    @RequestMapping("/edit")
    public String edit(Model model, String id) {
        Permission permission = new Permission();

        if (Misc.isNotEmpty(id)) permission = permissionService.getById(id);

        model.addAttribute("permission", permission);
        return managerPage("permission/edit");
    }

    @RequestMapping("/add")
    public String add(Permission permission) {
        permissionService.save(permission);
        return redirect("/managerPermission/list");
    }

    @ResponseBody
    @RequestMapping("/getPermission")
    public String getPermission() {
        List<Permission> data = permissionService.findAll();

        for (int i = 0; i < data.size(); i++) { data.get(i).setRoles(null); }

        return toJson(true, "success", data);
    }
}
